package com.xuecheng.fastdfs.demo;

import com.xuecheng.fastdfs.stub.HelloServiceGrpc;
import com.xuecheng.fastdfs.stub.HelloServiceOuterClass;
import io.grpc.Server;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class MyHelloServer extends HelloServiceGrpc.HelloServiceImplBase {

    @Override
    public void sayHello(HelloServiceOuterClass.HelloRequest request, StreamObserver<HelloServiceOuterClass.HelloResponse> responseObserver) {
        int requestId = request.getRequestId();
        String requestName = request.getName();
        HelloServiceOuterClass.HelloResponse response = HelloServiceOuterClass.HelloResponse.newBuilder()
                .setResponseId(requestId)
                .setResponseState(true)
                .setGreeting("Hello " + requestName + "! This greeting is from server!")
                .build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    public static void main(String[] args) {
        // 设置服务端口号
        int port = 8899;
        Server server = NettyServerBuilder.forPort(port)
                .addService(new MyHelloServer())
                .build();
        try {
            // 启动服务
            server.start();
            System.out.println("gRPC server started, on port: " + port);
            // 设置60秒后关闭
            server.awaitTermination(60, TimeUnit.SECONDS);
            System.out.println("gRPC server terminated.");
        } catch (IOException e) {
            System.out.println("Start server exception: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("Server interrupted: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
